package com.imc.core.utils;

import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
*类描述：map转对象，对象转map
*开发者：QY
*创建时间：2018/10/26 12:45
**/
@Component
public class TypeConversion {
    public Object mapToObject(Map<String,Object>map,Class<?> beanClass){
        if(map == null){
            return null;
        }
        try{
            Object obj=beanClass.newInstance();
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
            return obj;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public Map<String,Object>objectToMap(Object object){
        if(object == null){
            return null;
        }
        try{
            Map<String,Object>map=new HashMap<>();

            Field[] declaredFields = object.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(object));
            }
            return map;
        }catch (Exception e){
            return null;
        }

    }
}
